﻿
let transportType = signalR.TransportType[getParameterByName('transport')] || signalR.TransportType.WebSockets;
let logger = new signalR.ConsoleLogger(signalR.LogLevel.Information);
let connection = new signalR.HubConnection('/chat', { transport: transportType, logger: logger });

connection.onclose(e => {
	if (e) {
		appendLine('Connection closed with error: ' + e, 'red');
	}
	else {
		appendLine('Disconnected', 'green');
	}
});

connection.on('SetUsersOnline', usersOnline => {
	$(usersOnline).each(function (index, user) {
		addUserOnline(user);

	});
	//usersOnline.forEach(user => addUserOnline(user));
});

connection.on('UsersJoined', users => {
	console.log(JSON.stringify(users));
	$(users).each(function (index, user) {
		appendLine('User ' + user.name + ' 进入房间');
		addUserOnline(user);

	});
	//users.forEach(user => {
	//	appendLine('User ' + user.name + ' joined the chat');
	//	addUserOnline(user);
	//});
});

connection.on('UsersLeft', users => {
	console.log(JSON.stringify(users));
	$(users).each(function (index, user) {
		appendLine('User ' + user.name + ' 离开房间');
		document.getElementById(user.connectionId).outerHTML = '';

	});
	//users.forEach(user => {
	//	appendLine('User ' + user.name + ' left the chat');
	//	document.getElementById(user.connectionId).outerHTML = '';
	//});
});

connection.on('Send', (userName, message, toUserId, dateTime) => {
	log("发送");
	AddChatMsg(message, userName, toUserId, dateTime);
});
function AddChatMsg(message, sendUserId, toUserId, dateTime) {
	//<li class="chatli" >
	//	<span class="msg-time"></span>
	//	<span class="msg-role"></span><span class="msg-name"></span>
	//	<span class="msg-content" style="color: inherit; font-size: inherit"></span>
	//</li>
	 
	var timeElement = document.createElement('span');
	timeElement.className = 'msg-time';
	timeElement.innerText = dateTime;

	var roleElement = document.createElement('span');
	roleElement.className = 'msg-role';
	roleElement.innerText = ''; 

	var nameElement = document.createElement('span');
	nameElement.className = 'msg-name';
	nameElement.innerText = sendUserId;

	var contentElement = document.createElement('span');
	contentElement.className = 'msg-content';
	contentElement.style = 'color: inherit; font-size: inherit';
	

	if ((toUserId + "").length > 0) {
		contentElement.innerText += " @" + toUserId + " "; //实现@某人功能
	}
	contentElement.innerHTML += message;
 

	var child = document.createElement('li');
	child.className = 'chatli';
	child.appendChild(timeElement);
	//child.appendChild(roleElement);
	child.appendChild(nameElement);
	child.appendChild(contentElement);
	document.getElementById('messages').appendChild(child);
	MsgScrollTop();
	 
}
//是否停止滚动 默认是自动滚动的
let chatStopScrollScreen = false;
function MsgScrollTop() {
	try { 
		if (!chatStopScrollScreen) {
			$('#chatListOut').scrollTop($('#messages').height());

		}

	} catch (e) {
		console.log(e);
	}
}
connection.start().catch(err => appendLine(err, 'red'));

var lastTime = nowSeconds();
var sendCount = 0;
document.getElementById('btnSend').addEventListener('click', event => {

	var ntime = nowSeconds();
	if (ntime > lastTime + 10) {
		lastTime = ntime;
		sendCount = 0;
	}
	else {
		if (sendCount > 2) {
			window.alert('您发言的速度有点快，请先歇息10秒');
			return;
		}
	}
	sendCount += 1;

	let data = document.getElementById('txtContent').value;
	let roomId = document.getElementById("txtRoomId").value;
	let toUserId = document.getElementById("txtToUserId").value;
	connection.invoke('Send', replace_em( data), roomId, toUserId).catch(err => appendLine(err, 'red'));
	event.preventDefault();
});

//选中用户进行私聊
document.getElementById("users").addEventListener("click", event => {

	console.log("选中用户进行私聊:" + `${event.toElement.value}`);


	document.getElementById("txtToUserId").value = event.toElement.innerText;
	event.preventDefault();

});


function appendLine(line, color) {
	return;
	let child = document.createElement('li');
	
	if (color) {
		child.style.color = color;
	}
	child.innerText = line;
	document.getElementById('messages').appendChild(child);
};

function addUserOnline(user) {
	if (document.getElementById(user.name)) {
		return;
	} 
	if (document.getElementById(user.connectionId)) {
		return;
	} 
	if (user.roomId != parseInt( room.Id)) return;


	var userLi = document.createElement('li');
	userLi.className = 'role_member6';
	userLi.innerText = `${user.name}`;
	userLi.id = user.name;
	document.getElementById('users').appendChild(userLi);
}

function getParameterByName(name, url) {
	if (!url) {
		url = window.location.href;
	}
	name = name.replace(/[\[\]]/g, "\\$&");
	var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
		results = regex.exec(url);
	if (!results) return null;
	if (!results[2]) return '';
	return decodeURIComponent(results[2].replace(/\+/g, " "));
};

function log(msg) { console.log(msg);}